package com.zhonghan.recharge.service.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;

import com.qianmi.open.api.ApiException;
import com.qianmi.open.api.DefaultOpenClient;
import com.qianmi.open.api.OpenClient;
import com.qianmi.open.api.QianmiResponse;
import com.qianmi.open.api.request.BmGasCardPayBillRequest;
import com.qianmi.open.api.request.BmRechargeMobileGetPhoneInfoRequest;
import com.qianmi.open.api.request.GasCardGetAccountInfoRequest;
import com.qianmi.open.api.response.BmGasCardPayBillResponse;
import com.qianmi.open.api.response.BmRechargeMobileGetPhoneInfoResponse;
import com.qianmi.open.api.response.GasCardGetAccountInfoResponse;
import com.qianmi.open.api.tool.util.SignUtil;
import com.zhonghan.common.utils.BanMaSignUtil;
import com.zhonghan.common.utils.BanMaUtils;

/**
 * 充油业务
 * @author Administrator
 *
 */
public class Backup_RechargeServiceImpl{

	private String api_url="http://api.bm001.com/api";
	private String api_url_1 = "http://test.api.bm001.com/api";
	private String province = "全国";
	private String cardInfoMethod="bm.elife.gasCard.getAccountInfo";
	//支付加油卡订单
	private String oilRechargeMethod="bm.elife.gasCard.payBill";
	
	
	@Value("${qianmi.appKey}")
	private String APP_KEY;

	@Value("${qianmi.appSecret}")
	private String APP_SECRET;
	
	/*@Value("${qianmi.API_URL}")
	private String API_URL;
	*/
	
	//protected final 
	
	// 创建一个客户端，默认连接超时时间为3秒，请求超时时间为15秒。
    //protected OpenClient client = new DefaultOpenClient(API_URL, APP_KEY, APP_SECRET);
    
    public String getPhoneInfo(String operator,String gasCardNo) {
		
		/*
		 * 1.获取数字签名
		 * 1.1 拼接url  ：  bm_api+param
		 * 2.创建一个客户端对象
		 * 3.请求bm的api
		 * 4.处理响应信息
		 */
		
        try {
        	Map<String, String> param = new HashMap<>();
    		param.put("access_token", BanMaUtils.TOKEN);
            param.put("v", "1.1");
            param.put("method", "bm.elife.recharge.mobile.getPhoneInfo");
            String nowDate = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
            //param.put("timestamp", nowDate);
            param.put("format", "json");
            param.put("phoneNo", "18672715876");
            //param.put("respType", "all");
			String sign = BanMaSignUtil.sign(param, APP_SECRET);
			//时间替换
			//param.put("timestamp", nowDate.replaceAll(" ", "+").replaceAll(":", "%3A"));
			String param1 = urlStr(param);
			
			//拼接url
			String url = api_url_1+"?sign="+sign+"&"+param1;
			//获取客户端对象
			System.out.println(url);
			OpenClient client = new DefaultOpenClient(url, APP_KEY, APP_SECRET);
			BmRechargeMobileGetPhoneInfoRequest req = new BmRechargeMobileGetPhoneInfoRequest();
			req.setPhoneNo("18672715876");
			req.setRespType("all");
			BmRechargeMobileGetPhoneInfoResponse response = client.execute(req, BanMaUtils.TOKEN);
			
			/*OpenClient client = new DefaultOpenClient(url,APP_KEY, APP_SECRET);
			BmGasCardGetAccountInfoRequest req = new BmGasCardGetAccountInfoRequest();
			req.setProvince(province);
			req.setOperator(operator);
			req.setGasCardNo(gasCardNo);
			BmGasCardGetAccountInfoResponse response = client.execute(req, BanMaUtils.TOKEN);*/
			
			if (!response.isSuccess()) {
	            handleError(response);
	            return "getAccountInfo-fail";
	        }
			String body = response.getBody();
			System.out.println("查询到的信息"+body);
			return body;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
    
	public String getRechargeCardInfo(String operator,String gasCardNo) {
		
		/*
		 * 1.获取数字签名
		 * 1.1 拼接url  ：  bm_api+param
		 * 2.创建一个客户端对象
		 * 3.请求bm的api
		 * 4.处理响应信息
		 */
		
        try {
        	/*Map<String, String> param = new HashMap<>();
    		param.put("access_token", BanMaUtils.TOKEN);
            param.put("v", "1.1");
            param.put("method", cardInfoMethod);
            String nowDate = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
            param.put("timestamp", nowDate);
            param.put("province", province);
            param.put("operator", operator);
            param.put("gasCardNo", gasCardNo);
			String sign = BanMaSignUtil.sign(param, APP_SECRET);
			System.out.println("sign="+sign);
			//时间替换
			param.put("timestamp", nowDate.replaceAll(" ", "+").replaceAll(":", "%3A"));
			String param1 = urlStr(param);*/
			
		/*	//拼接url
			String url = api_url+"?"+param1+"&sign="+sign;
        	OpenClient client = new DefaultOpenClient(url,APP_KEY, APP_SECRET);
			BmGasCardGetAccountInfoRequest req = new BmGasCardGetAccountInfoRequest();
			req.setProvince(province);
			req.setOperator(operator);
			req.setGasCardNo(gasCardNo);
			BmGasCardGetAccountInfoResponse response = client.execute(req, BanMaUtils.TOKEN);*/
        	
			
			/*String url = api_url+"?"+param1+"&sign="+sign;
			OpenClient openClient = new DefaultOpenClient(url, APP_SECRET);*/
        	System.out.println(api_url+";");
    		System.out.println(APP_KEY+";");
    		System.out.println(APP_SECRET+";");
        	OpenClient client = new DefaultOpenClient(api_url_1, APP_KEY, APP_SECRET);
			//获取客户端对象
			//openClient
        	 GasCardGetAccountInfoRequest req = new GasCardGetAccountInfoRequest();
             req.setProvince("全国");
     		req.setOperator("sinopec");
     		req.setGasCardNo("1000119000002819544");
     		GasCardGetAccountInfoResponse response = client.execute(req, BanMaUtils.TOKEN);
     		if (!response.isSuccess()) {
                 handleError(response);
                 return "create-bill-fail";
             }
			
			
			
			
			if (!response.isSuccess()) {
	            handleError(response);
	            return "getAccountInfo-fail";
	        }
			String body = response.getBody();
			System.out.println("查询到的信息"+body);
			return body;
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		return null;
	}
	public String urlStr(Map<String, String> param) {
		StringBuilder strBuilder = new StringBuilder();
		Iterator<String> iterator = param.keySet().iterator();
		while(iterator.hasNext()) {
			String key = iterator.next();
			strBuilder.append(key+"="+param.get(key)).append("&");
		}
		return strBuilder.deleteCharAt(strBuilder.length()-1).toString();
	}
	private void handleError(QianmiResponse response) {
        System.out.println(response.getSubCode() + ":" + response.getSubMsg());
        // handle the error
    }
	
	/**
	 * 充油 
	 * gasnumber 持卡 卡号
	 * gasname   持卡人姓名
	 * gasphone  持卡人电话
	 * recardno 充值卡 卡号
	 * password 充值卡 密码
	 */
	public void oilRechargeBill(String gasnumber,String gasname, String gasphone,String recardno, String password){
		/**
		 * 1.根据充值卡 卡号，密码，获取面额，获取斑马商品id,固定面额 不需要
		 * 2.本地生成order ，获取orderno 
		 * 1 签名
		 * method= oilRechargeMethod
		 */
		String itemId="100000";
		double facePrice = 100d;
		String orderId="20180115110535";
		//订单回调 请求
		String callback = "www.zhkjnet.com/recharge/oil/callback";
		
		
		try {
			Map<String, String> param = new HashMap<>();
			//系统参数
			param.put("access_token", BanMaUtils.TOKEN);
	        param.put("v", "1.1");
	        param.put("method", oilRechargeMethod);
	        param.put("timestamp", (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
	        //方法参数  itemId   gasCardTel  gasCardName  gasCardNo  province  rechargeAmount(暂不)  outerTid   callback(暂不)
	        param.put("itemId", itemId);
	        param.put("province", province);
	        param.put("gasCardTel", gasphone);
	        param.put("gasCardName", gasname);
	        param.put("gasCardNo", gasnumber);
	        param.put("outerTid", orderId);
	        param.put("callback", callback);
			String sign = SignUtil.sign(param, APP_SECRET);
			
			String url = api_url+"?"+urlStr(param)+"&sign="+sign;
			OpenClient client = new DefaultOpenClient(url,APP_KEY, APP_SECRET);
			BmGasCardPayBillRequest req = new BmGasCardPayBillRequest();
			req.setItemId(itemId);
			req.setGasCardTel(gasphone);
			req.setGasCardName(gasname);
			req.setGasCardNo(gasnumber);
			req.setCallback(callback);
			BmGasCardPayBillResponse response = client.execute(req, BanMaUtils.TOKEN);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}
	
}
